#!/bin/sh
#
# --- BEGIN COPYRIGHT BLOCK ---
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2012 Red Hat, Inc.
# All rights reserved.
# --- END COPYRIGHT BLOCK ---
#

# The following variables are referenced in the sourced script
# /usr/share/pki/scripts/operations, to the error is invalid

# shellcheck disable=SC2034
PROG_NAME=`basename $0`
SERVICE_NAME="pkidaemon"
SERVICE_PROG="/bin/systemctl"

command="$1"
pki_instance_id="$2"

if [[ "$pki_instance_id" =~ .*"@".* ]]; then
    # instance ID contains <type>@<name>
    parts=(${pki_instance_id//@/ })
    pki_instance_type=${parts[0]}
    pki_instance_name=${parts[1]}

else
    # instance ID contains <name> only
    pki_instance_type="pki-tomcatd"
    pki_instance_name=$pki_instance_id
fi

PKI_REGISTRY="/etc/sysconfig/pki/tomcat"
PKI_SYSTEMD_TARGET="pki-tomcatd"

# Source the PKI function library
. /usr/share/pki/scripts/operations

print_usage()
{
    echo
    usage
    echo "where valid instance names include:"
    list_instances
    exit ${default_error}
}

# If the root user calls "pki-server run" command, the command
# will switch to PKI_USER to run the "pkidaemon" script which
# internally will execute a "find" command.

# The "find" command will go to another folder to do its job,
# then return to the current folder (e.g. /root). If PKI_USER
# has no access to that folder the "find" command will fail:
# https://unix.stackexchange.com/questions/474741/find-failed-to-restore-initial-working-directory-permission-denied

# To avoid the problem, switch to the instance folder first
# since it's owned by PKI_USER so there won't be a permission
# issue.

if [[ "$pki_instance_type" = "tomcat" ]]; then
    cd /var/lib/tomcats/${pki_instance_name}

else  # pki-tomcatd
    cd /var/lib/pki/${pki_instance_name}
fi

# See how we were called.
case $command in
    start)
        start
        exit $?
        ;;
    *)
        echo "unknown action ($command)"
        echo
        usage
        echo "where valid instance names include:"
        list_instances
        exit ${default_error}
        ;;
esac

